#!/usr/bin/env python
# coding:utf-8
""" 
@author: nivic ybyang7
@license: Apache Licence 
@file: server
@time: 2024/02/02
@contact: ybyang7@iflytek.com
@site:  
@software: PyCharm 

# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃　永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛ 
"""

#  Copyright (c) 2022. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
#  Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
#  Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
#  Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
#  Vestibulum commodo. Ut rhoncus gravida arcu.
from sparkai.depreciated.service import spark_ws
 
import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
 
# 以下密钥信息从控制台获取
appid = "e1081f9d"  # 填写控制台中获取的 APPID 信息
api_secret = "ZDlmNzQ2NzdjYzZkMjY3NGNjNzAzYzJj"  # 填写控制台中获取的 APISecret 信息
api_key = "337318a0efabfdba18e971767f7c32d7"  # 填写控制台中获取的 APIKey 信息
question = "user"

# 用于配置大模型版本，默认“general/generalv2”
domain = "lite"  # v1.5版本
# domain = "generalv2"    # v2.0版本
# 云端环境的服务地址
Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat"  # v1.5环境的地址

# 生成url
def create_url():
    # 生成RFC1123格式的时间戳
    now = datetime.now()
    # date = format_date_time(mktime(now.timetuple()))
    date = 'Tue, 15 Oct 2024 01:00:34 GMT'

    # 拼接字符串
    signature_origin = "host: " + "spark-api.xf-yun.com" + "\n"
    signature_origin += "date: " + date + "\n"
    signature_origin += "GET " + "/v1.1/chat" + " HTTP/1.1"

    # 进行hmac-sha256进行加密
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                                digestmod=hashlib.sha256).digest()

    signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')

    authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'

    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

    # 将请求的鉴权参数组合为字典
    v = {
        "authorization": authorization,
        "date": date,
        "host": "spark-api.xf-yun.com"
    }
    # 拼接鉴权参数，生成url
    url = "wss://spark-api.xf-yun.com/v1.1/chat?" + urlencode(v)
    #print("url = ", url)
    # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释，比对相同参数时生成的url与自己代码生成的url是否一致
    return url

if __name__ == '__main__':
    from sparkai.log.logger import logger

    logger.setLevel("debug")

    print("hello ai...")

    url = create_url()
    print("wsUrl = ", url)
    # spark_ws.answer = ""
    #spark_ws.main(appid, api_key, api_secret, Spark_url, domain, question) 
